package cn.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("download")
public class DownloadController {

    @RequestMapping("testEnv")
    public String test() {
        return "download env success.";
    }

    /**
     * 在后台Controller类中,使用Spring MVC提供的文件下载方法进行文件下载。
     * Spring MVC 提供了一个 ResponseEntity 对象,使用它可以很方便的定义返回的
     * HttpHeaders对象和HttpStatus对象,通过对这两个对象的设置,即可完成下载文件时所需的配置信息
     * TODO 文件下载报错,将来项目用到了再捣鼓吧...
     */
    @RequestMapping("test")
    public ResponseEntity<byte[]> test(HttpRequest request, String filename) throws IOException {
        String path = "src/main/resources";
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", filename);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }
}
